package com.example.thymeleaf.controller;

import com.example.thymeleaf.common.TokenUtils;
import com.example.thymeleaf.entity.UserEntity;
import com.example.thymeleaf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName UserController
 * @Author fuzhixuan
 * @Date 2022/1/29 14:26
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping(value = "/login")
    public String login() {
        return "/login";
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public String login1(@RequestBody UserEntity userEntity) {
        userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
        int count = userService.findUsers(userEntity);
        return count > 0 ? TokenUtils.token(userEntity.getUsername(), userEntity.getPassword()) : "fail";
    }

    @GetMapping(value = "/register")
    public String register() {
        return "/register";
    }

    @PostMapping(value = "/register")
    @ResponseBody
    public String register(@RequestBody UserEntity userEntity) {
        userEntity.setPassword(DigestUtils.md5DigestAsHex(userEntity.getPassword().getBytes()));
        userService.insertOne(userEntity);
        return "ok";
    }
}
